const { Form, Section, FieldType } = require('../models');
const { v4: uuidv4 } = require('uuid');

// 获取所有表单列表
const getAllForms = async (req, res) => {
  try {
    const {
      projectId,
      status,
      type,
      sortBy = 'order',
      sortOrder = 'asc',
      page = 1,
      limit = 10,
      search,
      name,
      code
    } = req.query;

    // 构建查询条件
    const query = {};
    
    if (projectId) {
      query.projectId = projectId;
    }

    if (status) query.status = status;
    if (type) query.type = type;

    // 搜索逻辑：
    // - 如果传入 name，则仅按名称模糊匹配
    // - 否则如果传入 search，则名称/编码混合匹配（兼容旧用法）
    // - 否则如果传入 code，则仅按编码模糊匹配
    if (typeof name === 'string' && name.trim()) {
      query.name = { $regex: name.trim(), $options: 'i' };
    } else if (typeof search === 'string' && search.trim()) {
      const keyword = search.trim();
      query.$or = [
        { name: { $regex: keyword, $options: 'i' } },
        { code: { $regex: keyword, $options: 'i' } }
      ];
    } else if (typeof code === 'string' && code.trim()) {
      query.code = { $regex: code.trim(), $options: 'i' };
    }

    // 构建排序条件
    const sortOptions = {};
    const allowedSortFields = ['order', 'createTime', 'updateTime', 'name', 'code'];
    const sortField = allowedSortFields.includes(sortBy) ? sortBy : 'order';
    const sortDirection = sortOrder === 'desc' ? -1 : 1;
    sortOptions[sortField] = sortDirection;

    const pageNum = parseInt(page, 10);
    const limitNum = parseInt(limit, 10);
    const skip = (pageNum - 1) * limitNum;

    const total = await Form.countDocuments(query);
    const forms = await Form.find(query)
      .sort(sortOptions)
      .skip(skip)
      .limit(limitNum)
      .populate('sectionId', 'name');

    res.json({
      success: true,
      data: forms,
      pagination: {
        total,
        page: pageNum,
        limit: limitNum,
        pages: Math.ceil(total / limitNum)
      }
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取表单列表失败',
      error: error.message
    });
  }
};

// 获取章节下的表单列表
const getForms = async (req, res) => {
  try {
    const { sectionId } = req.params;
    const { sortBy = 'order', sortOrder = 'asc' } = req.query;

    // 验证章节是否存在
    const section = await Section.findById(sectionId);
    if (!section) {
      return res.status(404).json({
        success: false,
        message: '章节未找到'
      });
    }

    // 构建排序条件
    const sortOptions = {};
    const allowedSortFields = ['order', 'createTime', 'updateTime', 'name', 'code'];
    const sortField = allowedSortFields.includes(sortBy) ? sortBy : 'order';
    const sortDirection = sortOrder === 'desc' ? -1 : 1;
    sortOptions[sortField] = sortDirection;

    const forms = await Form.find({ sectionId })
      .sort(sortOptions);

    res.json({
      success: true,
      data: forms
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取表单列表失败',
      error: error.message
    });
  }
};

// 获取表单详情
const getForm = async (req, res) => {
  try {
    const { id } = req.params;

    const form = await Form.findById(id)
      .populate('sectionId', 'name');

    if (!form) {
      return res.status(404).json({
        success: false,
        message: '表单未找到'
      });
    }

    res.json({
      success: true,
      data: form
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '获取表单详情失败',
      error: error.message
    });
  }
};

// 创建独立表单（不关联章节）
const createStandaloneForm = async (req, res) => {
  try {
    const { projectId, sectionId, ...formData } = req.body;

    // 如果提供了 projectId，检查项目是否存在
    if (projectId) {
      const project = await require('../models').Project.findById(projectId);
      if (!project) {
        return res.status(404).json({
          success: false,
          message: '项目未找到'
        });
      }
      }

      // 检查同一项目内表单编码是否重复（code 可选，提供时才校验）
    if (projectId && formData.code) {
      const existingForm = await Form.findOne({ 
        code: formData.code, 
        projectId: projectId 
      });
      if (existingForm) {
        return res.status(400).json({
          success: false,
          message: '表单编码在该项目中已存在'
        });
      }
    }

    const formPayload = {
      ...formData,
      projectId: projectId || null,
      sectionId: sectionId || null,
      order: formData.order || 1
    };

    // 处理字段ID
    if (formPayload.config?.fields) {
      formPayload.config.fields = formPayload.config.fields.map(field => ({
        ...field,
        id: field.id || uuidv4(),
        metadata: {
          ...field.metadata,
          createdAt: new Date(),
          updatedAt: new Date(),
          version: 1
        }
      }));
    }

    const form = new Form(formPayload);
    await form.save();

    // 如果关联了章节，更新章节的forms数组
    if (sectionId) {
      await Section.findByIdAndUpdate(
        sectionId,
        { $addToSet: { forms: form._id } }
      );
    }

    res.status(201).json({
      success: true,
      message: '表单创建成功',
      data: form
    });
  } catch (error) {
    if (error.code === 11000) {
      return res.status(400).json({
        success: false,
        message: '表单编码已存在'
      });
    }
    res.status(500).json({
      success: false,
      message: '创建表单失败',
      error: error.message
    });
  }
};

// 创建表单（在章节下）
const createForm = async (req, res) => {
  try {
    const { sectionId } = req.params;
    
    // 验证章节是否存在
    const section = await Section.findById(sectionId);
    if (!section) {
      return res.status(404).json({
        success: false,
        message: '章节未找到'
      });
    }

    // 检查同一项目内表单编码是否重复（code 可选，提供时才校验）
    if (req.body.code) {
      const existingForm = await Form.findOne({ 
        code: req.body.code, 
        projectId: section.projectId 
      });
      if (existingForm) {
        return res.status(400).json({
          success: false,
          message: '表单编码在该项目中已存在'
        });
      }
    }

    // 如果没有指定顺序，设置为最后一个
    if (!req.body.order) {
      const lastForm = await Form.findOne({ sectionId }).sort({ order: -1 });
      req.body.order = lastForm ? lastForm.order + 1 : 1;
    }

    const formData = {
      ...req.body,
      sectionId,
      projectId: section.projectId
    };

    // 处理字段ID
    if (formData.config?.fields) {
      formData.config.fields = formData.config.fields.map(field => ({
        ...field,
        id: field.id || uuidv4(),
        metadata: {
          ...field.metadata,
          createdAt: new Date(),
          updatedAt: new Date(),
          version: 1
        }
      }));
    }

    const form = new Form(formData);
    await form.save();

    // 更新章节的forms数组
    await Section.findByIdAndUpdate(
      sectionId,
      { $addToSet: { forms: form._id } }
    );

    await form.populate('sectionId', 'name');

    res.status(201).json({
      success: true,
      message: '表单创建成功',
      data: form
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '创建表单失败',
      error: error.message
    });
  }
};

// 更新表单基本信息
const updateForm = async (req, res) => {
  try {
    const { id } = req.params;

    const form = await Form.findById(id);
    if (!form) {
      return res.status(404).json({
        success: false,
        message: '表单未找到'
      });
    }

    // 如果更新编码，检查项目内是否重复（允许为空）
    if (req.body.code && req.body.code !== form.code) {
      const existingForm = await Form.findOne({ 
        code: req.body.code, 
        projectId: form.projectId,
        _id: { $ne: id }
      });
      if (existingForm) {
        return res.status(400).json({
          success: false,
          message: '表单编码在该项目中已存在'
        });
      }
    }

    const updatedForm = await Form.findByIdAndUpdate(
      id,
      req.body,
      { new: true, runValidators: true }
    ).populate('sectionId', 'name');

    res.json({
      success: true,
      message: '表单更新成功',
      data: updatedForm
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '更新表单失败',
      error: error.message
    });
  }
};

// 更新表单配置
const updateFormConfig = async (req, res) => {
  try {
    const { id } = req.params;
    
    console.log('=== DEBUG updateFormConfig ===');
    console.log('Request body type:', typeof req.body);
    console.log('Request body keys:', Object.keys(req.body));
    console.log('Fields type:', typeof req.body.fields);
    console.log('Fields is array:', Array.isArray(req.body.fields));
    
    const form = await Form.findById(id);
    if (!form) {
      return res.status(404).json({
        success: false,
        message: '表单未找到'
      });
    }

    // 确保fields是数组
    let fields = req.body.fields;
    if (typeof fields === 'string') {
      console.log('Fields is string, attempting to parse...');
      try {
        fields = JSON.parse(fields);
      } catch (e) {
        console.error('Failed to parse fields string:', e.message);
        return res.status(400).json({
          success: false,
          message: '字段数据格式错误',
          error: 'Invalid fields format'
        });
      }
    }

    if (!Array.isArray(fields)) {
      return res.status(400).json({
        success: false,
        message: '字段必须是数组格式',
        error: 'Fields must be an array'
      });
    }

    // 处理字段数据，确保每个字段都有必要的属性
    const processedFields = fields.map(field => {
      const existingField = form.config?.fields?.find(f => f.id === field.id);
      
      return {
        id: field.id || uuidv4(),
        type: field.type,
        name: field.name || field.id,
        label: field.label || field.name || '未命名字段',
        required: Boolean(field.required),
        visible: field.visible !== false,
        value: field.value || {},
        validations: Array.isArray(field.validations) ? field.validations : [],
        fieldConfig: field.fieldConfig || {},
        metadata: {
          createdAt: existingField?.metadata?.createdAt || new Date(),
          updatedAt: new Date(),
          version: (existingField?.metadata?.version || 0) + 1
        }
      };
    });

    console.log('Processed fields count:', processedFields.length);
    console.log('Sample field:', processedFields[0]);

    // 校验并确保同一表单内字段OID唯一
    const seen = new Set();
    for (let i = 0; i < processedFields.length; i++) {
      let fid = processedFields[i].id;
      if (!fid || seen.has(fid)) {
        // 重复或缺失则重新分配，直到唯一
        do { fid = uuidv4(); } while (seen.has(fid));
        processedFields[i].id = fid;
      }
      seen.add(fid);
    }

    // 构建新的配置对象
    const updateData = {
      'config.fields': processedFields
    };

    // 处理表单配置
    if (req.body.formConfig) {
      updateData['config.formConfig'] = req.body.formConfig;
    }

    // 添加最后更新时间
    if (req.body.lastUpdated) {
      updateData['config.lastUpdated'] = new Date(req.body.lastUpdated);
    }

    console.log('Update data keys:', Object.keys(updateData));

    // 使用$set操作符进行更新，避免类型转换问题
    const updatedForm = await Form.findByIdAndUpdate(
      id,
      { $set: updateData },
      { 
        new: true, 
        runValidators: false,  // 禁用验证器避免类型冲突
        strict: false          // 允许灵活的字段结构
      }
    ).populate('sectionId', 'name');

    console.log('Update successful, fields count:', updatedForm.config.fields.length);

    res.json({
      success: true,
      message: '表单配置更新成功',
      data: updatedForm
    });
  } catch (error) {
    console.error('updateFormConfig error details:', {
      message: error.message,
      name: error.name,
      stack: error.stack
    });
    
    res.status(500).json({
      success: false,
      message: '更新表单配置失败',
      error: error.message
    });
  }
};

// 删除表单
const deleteForm = async (req, res) => {
  try {
    const { id } = req.params;

    const form = await Form.findById(id);
    if (!form) {
      return res.status(404).json({
        success: false,
        message: '表单未找到'
      });
    }

    // 从章节的forms数组中移除
    await Section.findByIdAndUpdate(
      form.sectionId,
      { $pull: { forms: id } }
    );

    // 删除表单
    await Form.findByIdAndDelete(id);

    res.json({
      success: true,
      message: '表单删除成功'
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '删除表单失败',
      error: error.message
    });
  }
};

// 添加字段
const addField = async (req, res) => {
  try {
    const { id } = req.params;

    const form = await Form.findById(id);
    if (!form) {
      return res.status(404).json({
        success: false,
        message: '表单未找到'
      });
    }

    // 验证字段类型是否存在
    const fieldType = await FieldType.findOne({ type: req.body.type, isActive: true });
    if (!fieldType) {
      return res.status(400).json({
        success: false,
        message: '无效的字段类型'
      });
    }

    // 如果没有指定顺序，设置为最后一个
    if (!req.body.order) {
      const maxOrder = Math.max(...(form.config?.fields?.map(f => f.order) || [0]));
      req.body.order = maxOrder + 1;
    }

    const newField = {
      ...req.body,
      id: req.body.id || uuidv4(),
      metadata: {
        createdAt: new Date(),
        updatedAt: new Date(),
        version: 1
      }
    };

    // 如果没有value，使用字段类型的默认值
    if (!newField.value && fieldType.defaultConfig?.value) {
      newField.value = { ...fieldType.defaultConfig.value };
    }

    const updatedForm = await Form.findByIdAndUpdate(
      id,
      { $push: { 'config.fields': newField } },
      { new: true, runValidators: true }
    );

    res.json({
      success: true,
      message: '字段添加成功',
      data: newField
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '添加字段失败',
      error: error.message
    });
  }
};

// 更新字段
const updateField = async (req, res) => {
  try {
    const { id, fieldId } = req.params;

    const form = await Form.findById(id);
    if (!form) {
      return res.status(404).json({
        success: false,
        message: '表单未找到'
      });
    }

    const fieldIndex = form.config?.fields?.findIndex(f => f.id === fieldId);
    if (fieldIndex === -1) {
      return res.status(404).json({
        success: false,
        message: '字段未找到'
      });
    }

    const existingField = form.config.fields[fieldIndex];
    const updatedField = {
      ...existingField.toObject(),
      ...req.body,
      metadata: {
        ...existingField.metadata,
        updatedAt: new Date(),
        version: (existingField.metadata?.version || 0) + 1
      }
    };

    form.config.fields[fieldIndex] = updatedField;
    await form.save();

    res.json({
      success: true,
      message: '字段更新成功',
      data: updatedField
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '更新字段失败',
      error: error.message
    });
  }
};

// 删除字段
const deleteField = async (req, res) => {
  try {
    const { id, fieldId } = req.params;

    const form = await Form.findById(id);
    if (!form) {
      return res.status(404).json({
        success: false,
        message: '表单未找到'
      });
    }

    const updatedForm = await Form.findByIdAndUpdate(
      id,
      { $pull: { 'config.fields': { id: fieldId } } },
      { new: true }
    );

    res.json({
      success: true,
      message: '字段删除成功'
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '删除字段失败',
      error: error.message
    });
  }
};

// 复制表单
const copyForm = async (req, res) => {
  try {
    const { id } = req.params;
    const { targetSectionId, name, code } = req.body;

    const sourceForm = await Form.findById(id);
    if (!sourceForm) {
      return res.status(404).json({
        success: false,
        message: '源表单未找到'
      });
    }

    // 验证目标章节
    const targetSection = await Section.findById(targetSectionId);
    if (!targetSection) {
      return res.status(404).json({
        success: false,
        message: '目标章节未找到'
      });
    }

    // 检查编码是否重复
    const existingForm = await Form.findOne({ 
      code, 
      projectId: targetSection.projectId 
    });
    if (existingForm) {
      return res.status(400).json({
        success: false,
        message: '表单编码在目标项目中已存在'
      });
    }

    // 创建新表单
    const newFormData = {
      ...sourceForm.toObject(),
      _id: undefined,
      name: name || `${sourceForm.name} - 副本`,
      code,
      sectionId: targetSectionId,
      projectId: targetSection.projectId,
      createTime: new Date(),
      updateTime: new Date()
    };

    // 重新生成字段ID
    if (newFormData.config?.fields) {
      newFormData.config.fields = newFormData.config.fields.map(field => ({
        ...field,
        id: uuidv4(),
        metadata: {
          createdAt: new Date(),
          updatedAt: new Date(),
          version: 1
        }
      }));
    }

    const newForm = new Form(newFormData);
    await newForm.save();

    // 更新目标章节的forms数组
    await Section.findByIdAndUpdate(
      targetSectionId,
      { $addToSet: { forms: newForm._id } }
    );

    res.status(201).json({
      success: true,
      message: '表单复制成功',
      data: newForm
    });
  } catch (error) {
    res.status(500).json({
      success: false,
      message: '复制表单失败',
      error: error.message
    });
  }
};

module.exports = {
  getAllForms,
  getForms,
  getForm,
  createStandaloneForm,
  createForm,
  updateForm,
  updateFormConfig,
  deleteForm,
  addField,
  updateField,
  deleteField,
  copyForm
};